package study.springcloud.gateway.filter.global;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import study.springcloud.gateway.support.utils.RouteUtils;
import study.springcloud.gateway.support.utils.WebUtils;
import study.springcloud.gateway.support.utils.WriteUtils;

import java.util.Map;


@Slf4j
//@Component
public class RequestFilter implements GlobalFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //
        ServerHttpRequest request = WebUtils.getServerHttpRequest(exchange);

        // 头部
        log.info(">>>>>> 头部是否只读: {}", WebUtils.isReadOnly(request.getHeaders()));
        // request.getHeaders().add("fasdf", "fadsfsadf");
        // 路由
        Route route = RouteUtils.getRoute(exchange);
        log.info("{}", route.getId());
        // 属性
        Map<String, Object> data = exchange.getAttributes();
        data.entrySet().forEach(e -> {
            log.info("{}, {}", e.getKey(), e.getValue());
        });
        //
        log.info("请求 [{}] 转发给 [{}, {}]",
                RouteUtils.getOriginalRequestPath(exchange),
                RouteUtils.getGatewayRequestHost(exchange),
                RouteUtils.getGatewayRequestPath(exchange));

        //
        Mono<Void> mono;
        try {
            String source = WebUtils.getRequestHeader(exchange, "source");
            if (StrUtil.isEmpty(source)) {
                log.info("0000000");
                return WriteUtils.write(exchange, "source为空");
            }
            //
            mono = chain.filter(exchange);
        } finally {
            log.info("333333333333333");
        }
        return mono;
    }

}
